package com.ruoyi.ucar.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import com.obs.services.model.AccessControlList;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.ucar.boreq.SysFileBoReq;
import com.ruoyi.ucar.boresp.ObsImageBoResp;
import com.ruoyi.ucar.common.CommonVoResp;
import com.ruoyi.ucar.domain.SysFileMain;
import com.ruoyi.ucar.service.ISysFileMainService;
import com.ruoyi.ucar.util.CommonUtil;
import com.ruoyi.ucar.util.ResponseUtil;
import com.ruoyi.ucar.voreq.BatchFileUploadVoReq;
import com.ruoyi.ucar.voreq.FileUploadVoReq;
import com.ruoyi.ucar.voreq.ObsDownLoadFileVoReq;
import com.ruoyi.ucar.voresp.BatchFileUploadVoResp;
import com.ruoyi.ucar.voresp.FileUploadVoResp;
import com.ruoyi.ucar.voresp.ObsImageVoResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件附件主Controller
 * 
 * @author sungangbin
 * @date 2025-05-13
 */
@RestController
@RequestMapping("/ucar/main")
@Api(value = "文件管理",tags = "文件管理模块接口")
public class SysFileMainController extends BaseController
{

    @Autowired
    private ISysFileMainService sysFileMainService;




    /**
     * 查询文件附件主列表
     */
    @PreAuthorize("@ss.hasPermi('ucar:main:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysFileMain sysFileMain)
    {
        startPage();
        List<SysFileMain> list = sysFileMainService.selectSysFileMainList(sysFileMain);
        return getDataTable(list);
    }

    /**
     * 导出文件附件主列表
     */
    @PreAuthorize("@ss.hasPermi('ucar:main:export')")
    @Log(title = "文件导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFileMain sysFileMain)
    {
        List<SysFileMain> list = sysFileMainService.selectSysFileMainList(sysFileMain);
        ExcelUtil<SysFileMain> util = new ExcelUtil<SysFileMain>(SysFileMain.class);
        util.exportExcel(response, list, "文件附件主数据");
    }

    /**
     * 获取文件附件主详细信息
     */
    @PreAuthorize("@ss.hasPermi('ucar:main:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysFileMainService.selectSysFileMainById(id));
    }

    /**
     * 新增文件附件主
     */
    @PreAuthorize("@ss.hasPermi('ucar:main:add')")
    @Log(title = "文件附件主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysFileMain sysFileMain)
    {
        return toAjax(sysFileMainService.insertSysFileMain(sysFileMain));
    }

    /**
     * 修改文件附件主
     */
    @PreAuthorize("@ss.hasPermi('ucar:main:edit')")
    @Log(title = "文件附件主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysFileMain sysFileMain)
    {
        return toAjax(sysFileMainService.updateSysFileMain(sysFileMain));
    }

    /**
     * 删除文件附件主
     */
    @PreAuthorize("@ss.hasPermi('ucar:main:remove')")
    @Log(title = "文件附件主", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysFileMainService.deleteSysFileMainByIds(ids));
    }



    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传接口-通用")
    @Log(title = "文件上传日志",businessType = BusinessType.INSERT)
    public CommonVoResp<FileUploadVoResp> uploadFile( FileUploadVoReq fileUploadVoReq) {
        logger.info("文件上传入参：{}",fileUploadVoReq);
        CommonVoResp<FileUploadVoResp> commonVoResp = new CommonVoResp<>();
           MultipartFile file=fileUploadVoReq.getFile();
           String fileOldName=file.getOriginalFilename();
           String fileNewName=UUID.randomUUID().toString();
           String fileName = fileNewName+fileOldName;
           InputStream inputStream=null;
        try {
              inputStream=file.getInputStream();
//            obs上传文件
            String fileURl= sysFileMainService.obsUploadFile(fileName,inputStream, AccessControlList.REST_CANNED_PRIVATE);
//         数据库保存文件数据
            SysFileBoReq sysFileBoReq=new SysFileBoReq();
            sysFileBoReq.setFileOldName(fileOldName);
            sysFileBoReq.setFileNewName(fileName);
            sysFileBoReq.setFileUrl(fileURl);
            sysFileBoReq.setSort(0l);
            sysFileBoReq.setFileSize(new Long(file.getSize()).toString());
            sysFileBoReq.setFileFormat(FileNameUtil.extName(fileOldName));
            sysFileBoReq.setFileType("normalFile");
            String sysFileMainUUID= sysFileMainService.saveSysFile(sysFileBoReq);
            FileUploadVoResp fileVoResp = new FileUploadVoResp();
            fileVoResp.setLocation(fileURl);
            fileVoResp.setFileUuid(sysFileMainUUID);
            commonVoResp.setData(fileVoResp);
        } catch (IOException e) {
            commonVoResp = ResponseUtil.setCommonVoRespErrorFile(commonVoResp);
            logger.info("文件上传出参：{}",commonVoResp);
            return commonVoResp;
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                commonVoResp = ResponseUtil.setCommonVoRespErrorFile(commonVoResp);
                logger.info("文件上传出参：{}",commonVoResp);
                return commonVoResp;
            }
        }

        logger.info("文件上传出参：{}",commonVoResp);
        return commonVoResp;
    }
    @PostMapping("/batchUpload")
    @ApiOperation(value = "批量文件上传接口-通用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "批量文件",allowMultiple = true,required = true, dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    })
    @Log(title = "批量文件上传日志",businessType = BusinessType.INSERT)
    public CommonVoResp<BatchFileUploadVoResp> batchUpload(
            BatchFileUploadVoReq batchFileUploadVoReq) {
        logger.info("批量文件上传入参：{}",batchFileUploadVoReq);
        CommonVoResp<BatchFileUploadVoResp> commonVoResp = new CommonVoResp<>();
        BatchFileUploadVoResp batchFileUploadVoResp=new BatchFileUploadVoResp();
        List<String> batchLocations=new ArrayList<>();
        List<SysFileBoReq> sysFileBoReqList=new ArrayList<>();
    if(batchFileUploadVoReq.getFiles()!=null&&batchFileUploadVoReq.getFiles().length>0) {
     for (int index = 0; index < batchFileUploadVoReq.getFiles().length; index++) {
        MultipartFile file = batchFileUploadVoReq.getFiles()[index];
        String fileOldName = file.getOriginalFilename();
        String fileNewName = UUID.randomUUID().toString();
        String fileName = fileNewName + fileOldName;
        InputStream inputStream=null;
        try {
            inputStream=file.getInputStream();
            String fileURl = sysFileMainService.obsUploadFile( fileName,inputStream,AccessControlList.REST_CANNED_PRIVATE );
            batchLocations.add(fileURl);
            SysFileBoReq sysFileBoReq = new SysFileBoReq();
            sysFileBoReq.setFileOldName(fileOldName);
            sysFileBoReq.setFileNewName(fileName);
            sysFileBoReq.setFileUrl(fileURl);
            sysFileBoReq.setSort(new Long(index));
            sysFileBoReq.setFileSize(new Long(file.getSize()).toString());
            sysFileBoReq.setFileType("normalFile");
            sysFileBoReq.setFileFormat(FileNameUtil.extName(fileOldName));
            sysFileBoReqList.add(sysFileBoReq);
        } catch (IOException e) {
            commonVoResp = ResponseUtil.setCommonVoRespErrorFile(commonVoResp);
            logger.info("批量文件上传出参：{}",commonVoResp);
            return commonVoResp;
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                commonVoResp = ResponseUtil.setCommonVoRespErrorFile(commonVoResp);
                logger.info("批量文件上传出参：{}",commonVoResp);
                return commonVoResp;
            }
        }
     }
        String sysFileMainUUID=sysFileMainService.batchSaveSysFile(sysFileBoReqList);
        batchFileUploadVoResp.setFileUuid(sysFileMainUUID);
    }else{
        commonVoResp = ResponseUtil.setCommonVoRespNullFiles(commonVoResp);
        logger.info("批量文件上传出参：{}",commonVoResp);
        return commonVoResp;
    }
        batchFileUploadVoResp.setBatchLocations(batchLocations);
        commonVoResp.setData(batchFileUploadVoResp);
        logger.info("批量文件上传出参：{}",commonVoResp);
        return commonVoResp;
    }

    @PostMapping("/obsDownLoadFile")
    @Anonymous
    @ApiOperation(value = "下载文件接口-通用-匿名")
    public void obsDownLoadFile(@RequestBody ObsDownLoadFileVoReq obsDownLoadFileVoReq, HttpServletResponse response){
        logger.info("下载文件入参：{}",obsDownLoadFileVoReq);
        sysFileMainService.obsDownLoadFile(obsDownLoadFileVoReq.getFileMainUuid(),response);
    }

    @PostMapping("/obsDownloadImageToBase64String")
    @Anonymous
    @ApiOperation(value = "下载图片文件接口base64字符串-通用-匿名")
    public CommonVoResp<ObsImageVoResp> obsDownloadImageToBase64String(@RequestBody ObsDownLoadFileVoReq obsDownLoadFileVoReq){
        logger.info("下载图片文件接口-base64字符串入参：{}",obsDownLoadFileVoReq);
        CommonVoResp<ObsImageVoResp> commonVoResp = new CommonVoResp<>();
        ObsImageBoResp obsImageBoRes=  sysFileMainService.obsDownloadImageToBase64String(obsDownLoadFileVoReq.getFileMainUuid());
        if(obsImageBoRes!=null){
            commonVoResp.setData(CommonUtil.objToObj(obsImageBoRes, ObsImageVoResp.class));
            logger.info("下载图片文件接口-base64字符串出参：{}",commonVoResp);
            return commonVoResp;
        }else{
            commonVoResp = ResponseUtil.setCommonVoRespFail(commonVoResp);
            logger.info("下载图片文件接口-base64字符串出参：{}",commonVoResp);
            return commonVoResp;
        }
    }

}
